import 'dart:io';

import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:share_fit/app/helper/ext/tr_ext.dart';
import 'package:share_fit/app/models/home/sleep_model.dart';
import 'package:share_fit/app/tools/date_tool.dart';
import 'package:share_fit/generated/locales.g.dart';

class SleepBarChart extends StatefulWidget {
  SleepBarChart({super.key, required this.items});

  List<SleepModel> items = [];

  @override
  State<StatefulWidget> createState() => _SleepBarChartState();
}

class _SleepBarChartState extends State<SleepBarChart> {
  double fixedHeight = 90.h;

  /// 深睡
  final Color deepSleepColor = const Color.fromRGBO(110, 43, 182, 1);

  /// 浅睡
  final Color lightSleepColor = const Color.fromRGBO(152, 92, 247, 1);

  /// 清醒
  final Color awakeColor = const Color.fromRGBO(255, 196, 67, 1);

  /// 快速眼动
  final Color remColor = const Color.fromRGBO(40, 255, 253, 1);

  /// 零星小睡
  final Color napsColor = const Color.fromRGBO(253, 56, 197, 1);

  @override
  Widget build(BuildContext context) {
    String st = widget.items.isNotEmpty ? DateTool.getFullYMDHM(widget.items.first.startTime!).split(' ')[1] : '--:--';
    String et = widget.items.isNotEmpty ? DateTool.getFullYMDHM(widget.items.last.endTime!).split(' ')[1] : '--:--';

    return widget.items.isEmpty
        ? Center(child: Text(LocaleKeys.no_records_text.ts))
        : AspectRatio(
            aspectRatio: 1.66,
            child: LayoutBuilder(
              builder: (context, constraints) => Column(
                children: [
                  Expanded(
                    child: Stack(
                      children: [
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: [
                            SizedBox(height: 2.h),
                            Text(
                              LocaleKeys.sleep_rem_short_title_text.ts,
                              style: TextStyle(fontSize: 36.sp, overflow: TextOverflow.ellipsis, color: Colors.grey.withOpacity(.8)),
                            ),
                            SizedBox(
                              width: 100.w,
                              child: Text(
                                LocaleKeys.sleep_sober_text.ts,
                                style: TextStyle(fontSize: 36.sp, overflow: TextOverflow.ellipsis, color: Colors.grey.withOpacity(.8)),
                              ),
                            ),
                            SizedBox(
                              width: 100.w,
                              child: Text(
                                LocaleKeys.sleep_light_text.ts,
                                style: TextStyle(fontSize: 36.sp, overflow: TextOverflow.ellipsis, color: Colors.grey.withOpacity(.8)),
                              ),
                            ),
                            SizedBox(
                              width: 100.w,
                              child: Text(
                                LocaleKeys.sleep_deep_text.ts,
                                style: TextStyle(fontSize: 36.sp, overflow: TextOverflow.ellipsis, color: Colors.grey.withOpacity(.8)),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(width: 10.w),
                        BarChart(
                          BarChartData(
                            maxY: 400.h,
                            barTouchData: barTouchData,
                            titlesData: titlesData,
                            borderData: FlBorderData(
                              show: true,
                              border: Border(bottom: BorderSide(color: Colors.grey.withOpacity(.3))),
                            ),
                            barGroups: barGroups(constraints.maxWidth),
                            gridData: FlGridData(
                              show: true,
                              drawVerticalLine: false,
                              horizontalInterval: Platform.isAndroid ? 28 : 31,
                              getDrawingHorizontalLine: (value) => const FlLine(color: Colors.black12, strokeWidth: 1),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Row(
                    children: [
                      SizedBox(width: 50.w),
                      Text(st),
                      const Spacer(flex: 2),
                      Text(et),
                    ],
                  ),
                ],
              ),
            ),
          );
  }

  get barTouchData {
    return BarTouchData(
      enabled: true,
      longPressDuration: const Duration(milliseconds: 200),
      // handleBuiltInTouches: false,
      // touchCallback: (FlTouchEvent event, BarTouchResponse? response) {
      //   if (event.isInterestedForInteractions && response != null && response.spot != null) {
      //     setState(() {
      //       touchedGroupIndex = response.spot!.touchedBarGroupIndex;
      //       isTouched = true;
      //     });
      //   } else {
      //     setState(() {
      //       touchedGroupIndex = -1;
      //       isTouched = false;
      //     });
      //   }
      // },
      touchTooltipData: BarTouchTooltipData(
        fitInsideHorizontally: true,
        fitInsideVertically: false,
        direction: TooltipDirection.top,
        tooltipPadding: EdgeInsets.zero,
        tooltipMargin: 60.h,
        tooltipBgColor: Colors.grey.withOpacity(0.8),
        getTooltipItem: (BarChartGroupData group, int groupIndex, BarChartRodData rod, int rodIndex) {
          SleepModel sm = widget.items[groupIndex];
          return BarTooltipItem(
            dateTooltipText(sm),
            TextStyle(
              fontSize: 36.sp,
            ),
          );
        },
      ),
    );
  }

  String dateTooltipText(SleepModel sm) {
    DateTime startTime = DateTime.fromMillisecondsSinceEpoch(sm.startTime! * 1000);
    DateTime endTime = DateTime.fromMillisecondsSinceEpoch(sm.endTime! * 1000);
    return '${sm.sleepTypeText} ${DateTool.hsFormat(startTime)}~${DateTool.hsFormat(endTime)}';
  }

  List<BarChartGroupData> barGroups(double width) {
    int total = widget.items.isEmpty ? 0 : widget.items.map((e) => e.sleepTime ?? 0).reduce((value, element) => value + element);
    double percent = (width - 100.w) / total;
    return widget.items.map((item) => makeGroupData(item.sleepType!, (item.sleepTime! * percent).toInt())).toList();
  }

  get titlesData {
    return FlTitlesData(
      show: true,
      bottomTitles: AxisTitles(
        sideTitles: SideTitles(
          showTitles: true,
          getTitlesWidget: (value, meta) => Container(),
          reservedSize: 5,
        ),
      ),
      leftTitles: AxisTitles(
        sideTitles: SideTitles(
          reservedSize: 40,
          showTitles: true,
          getTitlesWidget: getLeftTitles,
          // interval: 58,
        ),
      ),
      topTitles: const AxisTitles(
        sideTitles: SideTitles(
          showTitles: false,
        ),
      ),
      rightTitles: const AxisTitles(
        sideTitles: SideTitles(
          showTitles: false,
        ),
      ),
    );
  }

  Widget getLeftTitles(double value, TitleMeta meta) {
    return Container(width: 100.w, margin: EdgeInsets.only(bottom: 20.h));
  }

  BarChartGroupData makeGroupData(int x, int y) {
    return BarChartGroupData(
      x: x,
      barRods: [
        BarChartRodData(
          fromY: (x - 1) * fixedHeight,
          toY: x * fixedHeight,
          color: getColor(x),
          borderRadius: BorderRadius.zero,
          width: y.toDouble(),
        ),
      ],
    );
  }

  getColor(int type) {
    switch (type) {
      case 1: //深睡
        return deepSleepColor;
      case 2: //浅睡
        return lightSleepColor;
      case 3: //清醒
        return awakeColor;
      case 4: //快速眼动
        return remColor;
      default:
        return napsColor;
    }
  }

  Widget getBottomTitles(double value, TitleMeta meta) {
    const style = TextStyle(
      color: Colors.white,
      fontWeight: FontWeight.bold,
      fontSize: 14,
    );
    List<String> days = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];

    Widget text = Text(
      days[value.toInt()],
      style: style,
    );

    return SideTitleWidget(
      axisSide: meta.axisSide,
      space: 16,
      child: text,
    );
  }
}
